// src/router/RequireAuth.tsx

import { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import type { FC, ReactElement } from 'react';
import { useUserStore } from '@/store/userStore';

interface RequireAuthProps {
  children: ReactElement;
}

const RequireAuth: FC<RequireAuthProps> = ({ children }) => {
  const { user, initUser } = useUserStore();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem('token');
      if (token) {
        if (!user.role) {
          try {
            await initUser();
          } catch (error) {
            console.error('Failed to initialize user:', error);
            localStorage.removeItem('token');
            setIsLoading(false);
            return;
          }
        }
        setIsLoading(false);
      } else {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, [user.role, initUser]);

  useEffect(() => {
    if (user.role && isLoading) {
      setIsLoading(false);
    }
  }, [user.role, isLoading]);

  if (user.role && !isLoading) {
    return children;
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  const token = localStorage.getItem('token');
  return token ? children : <Navigate to="/login" replace />;
};

export default RequireAuth;